<template>
  <div class="login">
    <el-form :model="form" label-width="120px" ref="loginFormRef" :rules="rules">
      <el-form-item label="登录名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="adminLogin" class="btn">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {reqAdminLogin} from '../../api/index';
import { ElMessage } from 'element-plus'
export default {
    name:'Login',
    data(){
      return {
        form:{
          name:'',
          password:''
        },
        rules:{
          name:[
            {required:true,message:'请输入登录名',trigger:'blur'}
          ],
          password:[
            {required:true,message:'请输入密码',trigger:'blur'},
            {min:1,max:15,message:'密码长度为1到15位',trigger:'blur'}  
          ]
        }
      }
    },
    methods:{
      async adminLogin(){
        let formDom = this.$refs.loginFormRef;
        if(!formDom)return;
        formDom.validate(async(valid,fields)=>{
          if(valid){
            let res = await reqAdminLogin(this.form.name,this.form.password);
            if(res.token){
              localStorage.token = res.token;
              this.$router.push('/');
              return;
            }
            ElMessage.error('登录名或密码错误');
            this.form.name = '';
            this.form.password = '';
            
          }else {
            console.log('error submit!', fields)
          }
        })
      }
    }
}
</script>

<style scoped>
  .login{
    width: 400px;
    position: absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
  }
  .btn{
    margin:0 auto;
  }
  .errMessage{
    text-align: center;
    color:red;
    margin-left:10px;
  }
</style>